﻿using UnityEngine;
using UnityEngine.Networking;

using System.Collections;
namespace demo5{
	public class Player : NetworkBehaviour {

		public GameObject cloneCarObject;
		// Use this for initialization
		void Start () {
		
		}
		[SyncVar]
		public Vector3 sysEuler;
		[SyncVar]
		public Vector3 sysPositon;

		// Update is called once per frame
		void Update () {
			if (!isLocalPlayer)
				return;
			float h = Input.GetAxis ("Horizontal");
			float v = Input.GetAxis ("Vertical");
			transform.Rotate (Vector3.up * h * 240 * Time.deltaTime);
			transform.Translate (Vector3.forward * v * Time.deltaTime * 5);

			if (Input.GetKeyDown (KeyCode.Q)) {
				GrabCar ();
			}

			if (Input.GetKeyDown (KeyCode.E)) {
				ThrowCar ();
			}

			if (Input.GetKeyDown (KeyCode.C)) {
				CmdCreateCar ();
			}


		}

		void FixedUpdate(){
			if (isLocalPlayer) {
				CmdPositonAndEuler (transform.position,transform.eulerAngles);
			}
			if (!isLocalPlayer) {
				RefreshPositonAndEuler ();
			}
		}

		[Command]
		void CmdPositonAndEuler(Vector3 _Position ,Vector3 _Euler){
			sysEuler = _Euler;
			sysPositon = _Position;
		}
		void RefreshPositonAndEuler(){
			transform.position = Vector3.Lerp (transform.position,sysPositon,Time.deltaTime * 15);
			transform.eulerAngles = Vector3.Lerp (transform.eulerAngles,sysEuler,Time.deltaTime * 15);
		}

		public Car _triggerCar = null;
		void OnTriggerEnter(Collider other){
			if (other.GetComponent<Car> ()!=null) {
				_triggerCar = other.GetComponent<Car> ();
			}
		}

		void OnTriggerExit(Collider other){
			
		}


		[Command]
		void CmdCreateCar(){
			GameObject _carObject = Instantiate (cloneCarObject, transform.position + transform.forward * 3, Quaternion.identity) as GameObject;
			NetworkServer.Spawn (_carObject);
			//NetworkClient.allClients;
			//NetworkServer.connections [i].connectionId;
		}

		[ClientCallback]
		void GrabCar(){

			if (_triggerCar != null) {
				//_triggerCar.transform.SetParent (transform);

				CmdGrabCar (_triggerCar.netId);
			}
		}


		[Command]
		void CmdGrabCar(NetworkInstanceId netid){

			GameObject obj =  NetworkServer.FindLocalObject (netid);
			if (obj) {
				RpcGrabCar (netid);
			}
		}

		[ClientRpc]
		void RpcGrabCar(NetworkInstanceId netid){

			GameObject obj = ClientScene.FindLocalObject (_triggerCar.netId);
			if (obj != null) {
				obj.transform.SetParent (transform);
			}
		}

		void ThrowCar(){
			if (_triggerCar != null) {
				CmdThrowCar (_triggerCar.netId);
			}
		}

		[Command]
		void CmdThrowCar(NetworkInstanceId netid){
			//NetworkServer.Destroy (null, 3);
			RpcThrowCar(netid);
		}

		[ClientRpc]
		void RpcThrowCar(NetworkInstanceId netid){

			GameObject obj = ClientScene.FindLocalObject (_triggerCar.netId);
			if (obj != null) {
				obj.transform.SetParent (null);
				obj.AddComponent<Rigidbody> ().AddForce (transform.forward *30000);
				Destroy (obj,3);
			}
		}

	}


}
